#!/bin/bash

source ./run_common.sh

set -x

APP=edu

if [ -n "$2" ] ;then
   do_date=$2
else 
   do_date=`date -d '-1 day' +%F`
fi

load_data(){
    sql=""
    for i in $*; do
        #判断路径是否存在
        hadoop fs -test -e /origin_data/$APP/db/${i:4}/$do_date
        #路径存在方可装载数据
        if [[ $? = 0 ]]; then
            sql=$sql"load data inpath '/origin_data/$APP/db/${i:4}/$do_date' OVERWRITE into table ${APP}.$i partition(dt='$do_date');"
        fi
    done
	
	echo "拼接后的SQL为：$sql"
	
    hive -e "$sql"
}

#=================================

input_param="$1"

if [[ -z "$input_param" ]]; then
  echo "请输入参数"
  exit 1
fi

#=================================

#定义一个数组
table_array=()

# 获取所有表名，并将结果保存到数组中
table_list=$(hive -e "use $APP; show tables;")
table_array=($table_list)

filtered_table_array=()

for table in "${table_array[@]}"; do

  if [[ $table == ods_* ]]; then
  
    if [[ $table != "ods_log_inc" ]]; then
  
      filtered_table_array+=("$table")
	
	fi
	
  fi
  
done

table_array=("${filtered_table_array[@]}")

# 输出数组中的表名
for table in "${table_array[@]}"; do
  echo "从数据库获取的表名为： $table"
done

#=================================

found=0

if [[ "$input_param" == "all" ]]; then

  found=1
  
  result=""
  
  for file in "${table_array[@]}"; do
	
	result+="\"$file\" "
    
  done
  
  # 删除最后一个空格
  result=${result%?}

  echo "拼接后的字符串为：${result}" 
  
  # 使用eval调用load_data
  eval "load_data $result"
  
else
  for file in "${table_array[@]}"; do
  
    if [[ "$file" == "$input_param" ]]; then
	
      found=1
      
	  load_data ${file}
	  
      break
    fi
  done
fi

if [[ $found -eq 0 ]]; then
  echo "参数错误"
  exit 1
fi

echo "执行成功"
